import React from 'react';
import 'frontend/public/stitics/css/index.css'; // 导入样式文件
import AddBookForm from './components/AddBookForm.js';
import BookList from './components/bookList.js';

function App() {
  const [books, setBooks] = useState([]);

  // 获取所有图书
  useEffect(() => {
    fetch('/api/books')
      .then(response => response.json())
      .then(data => setBooks(data))
      .catch(error => console.error('Error fetching books:', error));
  }, []);

  // 添加图书
  const addBook = async (book) => {
    try {
      const response = await fetch('/api/books', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(book),
      });
      const newBook = await response.json();
      setBooks([...books, newBook]);
    } catch (error) {
      console.error('Error adding book:', error);
    }
  };

  // 删除图书
  const deleteBook = async (id) => {
    try {
      await fetch(`/api/books/${id}`, {
        method: 'DELETE',
      });
      setBooks(books.filter(book => book._id !== id));
    } catch (error) {
      console.error('Error deleting book:', error);
    }
  };

  // 更新图书
  const updateBook = async (id, updatedBook) => {
    try {
      const response = await fetch(`/api/books/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedBook),
      });
      const updated = await response.json();
      setBooks(books.map(book => (book._id === id ? updated : book)));
    } catch (error) {
      console.error('Error updating book:', error);
    }
  };

  return (
    <div className="App">
      <h1>图书管理系统</h1>
      <AddBookForm onAddBook={addBook} />
      <BookList books={books} onDeleteBook={deleteBook} onUpdateBook={updateBook} />
    </div>
  );
}

export default App;
